﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Microsoft.Win32;

namespace EasyTrader.Form
{
    using PriceWaveList = List<EasyTrader.Wave.PriceWave>;
    using PricePointList = List<EasyTrader.Wave.PricePoint>;
    using PriceSignalList = List<EasyTrader.Signal.PriceSignal>;
    public partial class SimulationFrm : System.Windows.Forms.Form
    {
#region SysManager Event Handler
        public void UncheckAutoOrder(bool a_LastSignalFired, int a_SysType)
        {
            // 이벤트를 보낸 시스템과 현재 선택되어 있는 시스템이 일치하면 자동 주문을 체크를 해제해 준다.
            if (a_SysType == m_SysType)
            {
                cbAutoOrder.Checked = false;
            }
        }


        public void SysManager_OnLastSignalFired(object sender, EventArgs e)
        {
            EasyTrader.SysManagerEventArgs arg = (EasyTrader.SysManagerEventArgs)e;
            UncheckAutoOrder(arg.AutoOrder, arg.SysType);
        }

#endregion
        private string m_HashCode = "";
        public string HashCode
        {
            get { return m_HashCode; }
            set { m_HashCode = value; }
        }
        private int m_SysType = GlobalVar.SysTypeJisuWaveHogaSummit;
        public int SysType
        {
            get { return m_SysType; }
            set { m_SysType = value; }
        }

        private string m_SysName = "";
        private int m_FirstSig = GlobalVar.FirstSigByHogaAngle;

        private bool m_Started = false;
        private EasyTrader.Signal.ForecastingInfo m_ForecastInfo = new EasyTrader.Signal.ForecastingInfo();
        private EasyTrader.Signal.DirectionDetector m_Forecaster = new EasyTrader.Signal.DirectionDetector();
        private bool m_ShowSignal = true;
        private int m_CurIndex = 0;
        private bool ChartDataLoaded = false;
        private EasyTrader.Signal.TotalSignalManager m_EasyTraderSignalManager = null;
        public EasyTrader.Signal.TotalSignalManager EasyTraderSignalManager
        {
            get { return m_EasyTraderSignalManager; }
            set { m_EasyTraderSignalManager = value; }
        }


        public SimulationFrm()
        {
            InitializeComponent();
        }

         private void dateTimePickerCtrl_ValueChanged(object sender, EventArgs e)
        {
            DateTime curTime = dateTimePickerCtrl.Value;
            //GlobalVar.FutureCode = GlobalVar.GetFutureCode(curTime);
            GlobalVar.WorkDate = GlobalVar.DateToInt(curTime);

            if (m_CPDataSet == null)
                return;

            DateTime curDate = dateTimePickerCtrl.Value;
            m_CPDataSet.ReadTablesFromXML(curDate);
            int curDay = GlobalVar.DateToInt(curTime);
            m_CPDataSet.DownLoader.CurDay = curDay;
            m_CPDataSet.DownLoader.InitDownloadCount();
        }


         private void DrawSignal(PriceSignalList a_SignalList, ChartPaintEventArgs a_EventArg)
         {
             if (a_SignalList == null)
                 return;

             if (a_EventArg.ChartElement is ChartArea)
             {
                 ChartArea area = (ChartArea)a_EventArg.ChartElement;
                 if (area.Name == "Price")
                 {
                     double highXValue = 0;
                     double highYValue = 0;

                     Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                     Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                     FontStyle.Regular);

                     System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                     // Set the TextRenderingHint property.
                     graphics.TextRenderingHint =
                         System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                     string valueText = "";
                     //List<TrendWave> waveList = a_WaveList.WaveList;
                     for (int i = 0; i < a_SignalList.Count; i++)
                     {
                         EasyTrader.Signal.PriceSignal curSignal = a_SignalList[i];

                         highXValue = curSignal.X;
                         highYValue = curSignal.Y;

                         string curValue = String.Format("{0:F2}", curSignal.Y);

                         // Convert X and Y values to screen position
                         float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                         float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);
                         float pixelYMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                         float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);

                         // Specify width of triangle
                         float width = 1;

                         // Set Maximum points
                         PointF[] points = new PointF[3];
                         points[0].X = pixelXMax - width;
                         points[0].Y = pixelYMax - width - 2;
                         points[1].X = pixelXMax + width;
                         points[1].Y = pixelYMax - width - 2;
                         points[2].X = pixelXMax;
                         points[2].Y = pixelYMax - 1;

                         // Convert relative coordinates to absolute coordinates.
                         points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                         points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                         points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                         // 고점 변곡점 타입일 때. 하향을 향하므로 매도 사인을 낸다.
                         if (curSignal.Type == GlobalVar.SignalSell)
                         {
                             // Draw Maximum trangle
                             graphics.FillPolygon(new SolidBrush(Color.Blue), points);
                             string curTime = curSignal.Time.ToString();
                             if (curTime != "0")
                             {
                                 string minText = curTime.Substring(curTime.Length - 2, 2);
                                 string hourText = curTime.Substring(0, curTime.Length - 2);
                                 curTime = hourText + ":" + minText;
                             }
                             valueText = "매도[";
                             if (curSignal.SignalState == GlobalVar.SignalStateFirst)
                             {
                                 valueText += "초입";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateTrans)
                             {
                                 valueText += "전환";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateOver)
                             {
                                 valueText += "돌파";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateLiquid)
                             {
                                 valueText += "청산";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateCorrect)
                             {
                                 valueText += "수정";
                             }
                             else
                             {
                                 valueText += "없음";
                             }
                             valueText += "]";
                             valueText += "(" + curTime + " , " + curValue + ")";
                             // Draw the string.
                             graphics.DrawString(valueText, myFont,
                                 Brushes.Blue, points[2].X, points[2].Y - width);
                         }
                         if (curSignal.Type == GlobalVar.SignalExitBuy)
                         {
                             // Draw Maximum trangle
                             graphics.FillPolygon(new SolidBrush(Color.Green), points);
                             string curTime = curSignal.Time.ToString();
                             if (curTime != "0")
                             {
                                 string minText = curTime.Substring(curTime.Length - 2, 2);
                                 string hourText = curTime.Substring(0, curTime.Length - 2);
                                 curTime = hourText + ":" + minText;
                             }
                             valueText = "매도[";
                             
                                 valueText += "청산";
                             
                             valueText += "]";
                             valueText += "(" + curTime + " , " + curValue + ")";
                             // Draw the string.
                             graphics.DrawString(valueText, myFont,
                                 Brushes.Blue, points[2].X, points[2].Y - width);
                         }

                         // Set Minimum points
                         points = new PointF[3];
                         points[0].X = pixelXMin - width;
                         points[0].Y = pixelYMin + width + 2;
                         points[1].X = pixelXMin + width;
                         points[1].Y = pixelYMin + width + 2;
                         points[2].X = pixelXMin;
                         points[2].Y = pixelYMin + 1;

                         // Convert relative coordinates to absolute coordinates.
                         points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                         points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                         points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                         // 고점 변곡점 타입일 때. 상향을 향하므로 매수 사인을 낸다.
                         if (curSignal.Type == GlobalVar.SignalBuy)
                         {
                             // Draw Minimum triangle
                             graphics.FillPolygon(new SolidBrush(Color.Red), points);
                             string curTime = curSignal.Time.ToString();
                             if (curTime != "0")
                             {
                                 string minText = curTime.Substring(curTime.Length - 2, 2);
                                 string hourText = curTime.Substring(0, curTime.Length - 2);
                                 curTime = hourText + ":" + minText;
                             }
                             valueText = "매수[";
                             if (curSignal.SignalState == GlobalVar.SignalStateFirst)
                             {
                                 valueText += "초입";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateTrans)
                             {
                                 valueText += "전환";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateOver)
                             {
                                 valueText += "돌파";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateLiquid)
                             {
                                 valueText += "청산";
                             }
                             else if (curSignal.SignalState == GlobalVar.SignalStateCorrect)
                             {
                                 valueText += "수정";
                             }
                             else
                             {
                                 valueText += "없음";
                             }
                             valueText += "]";
                             valueText += "(" + curTime + " , " + curValue + ")";
                             // Draw the string.
                             graphics.DrawString(valueText, myFont,
                                 Brushes.Red, points[2].X, points[2].Y - 15);
                         }
                         if (curSignal.Type == GlobalVar.SignalExitSell)
                         {
                             // Draw Minimum triangle
                             graphics.FillPolygon(new SolidBrush(Color.Green), points);
                             string curTime = curSignal.Time.ToString();
                             if (curTime != "0")
                             {
                                 string minText = curTime.Substring(curTime.Length - 2, 2);
                                 string hourText = curTime.Substring(0, curTime.Length - 2);
                                 curTime = hourText + ":" + minText;
                             }
                             valueText = "매수[";
                             
                                 valueText += "청산";
                             
                             valueText += "]";
                             valueText += "(" + curTime + " , " + curValue + ")";
                             // Draw the string.
                             graphics.DrawString(valueText, myFont,
                                 Brushes.Red, points[2].X, points[2].Y - 15);
                         }
                     }
                 }
             }
         }

         private void DrawCredential(ChartPaintEventArgs a_EventArg)
         {
             if (a_EventArg.ChartElement is ChartArea)
             {
                 ChartArea area = (ChartArea)a_EventArg.ChartElement;
                 if (area.Name == "Price")
                 {
                     double highXValue = 0;
                     double highYValue = 0;

                     Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                     Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                     FontStyle.Regular);

                     System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                     // Set the TextRenderingHint property.
                     graphics.TextRenderingHint =
                         System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                     string msg = GlobalVar.CopyWriteMsg + "\n" + GlobalVar.Name + "\n" + GlobalVar.HP + "\n" + GlobalVar.EMail;


                     // Convert X and Y values to screen position
                     float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                     float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);
                     float pixelYMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                     float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);
                                         
                     // Draw the string.
                     graphics.DrawString(msg, myFont,
                         Brushes.Blue, pixelXMin, pixelYMin);
                     
                 }
             }
         }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer.Start();
            m_Started = true;
        }

        int curChartType = 0;
        // Wave Manager
        private EasyTrader.Wave.WaveManager m_WaveManager = new EasyTrader.Wave.WaveManager();
        public EasyTrader.Wave.WaveManager WaveManager
        {
            get { return m_WaveManager; }
            set { m_WaveManager = value; }
        }
        // Signal Manager
        private EasyTrader.Signal.SignalManager m_SignalManager = new EasyTrader.Signal.SignalManager();
        public EasyTrader.Signal.SignalManager SignalManager
        {
            get { return m_SignalManager; }
            set { m_SignalManager = value; }
        }
        // Cybos Plus Data Set Member
        private ETDataSet m_CPDataSet = null;
        public EasyTrader.ETDataSet CPDataSet
        {
            get { return m_CPDataSet; }
            set { m_CPDataSet = value; }
        }
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private void InitTimer()
        {
            timer.Interval = (int)nudTimerInterval.Value;
            timer.Tick += new EventHandler(OnTimerTick);
            //timer.Start();
        }

        private void SetWaveOnChart(PriceWaveList a_WaveList)
        {
            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["파동"].Points.Clear();
            for (int i = 0; i < a_WaveList.Count; i++)
            {
                EasyTrader.Wave.PriceWave wave = a_WaveList[i];
                SimulationChartCtrl.Series["파동"].Points.AddXY(wave.StartX, wave.StartY);
                // 파동은 마지막 점을 한번 더 넣어 준다.
                if (i == a_WaveList.Count - 1)
                {
                    SimulationChartCtrl.Series["파동"].Points.AddXY(wave.EndX, wave.EndY);
                }
            }
        }

        private void SetSignalWaveOnChart(EasyTrader.Wave.PriceWave a_Wave)
        {
            if (a_Wave == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["기상위"].Points.Clear();
            SimulationChartCtrl.Series["기하위"].Points.Clear();
            double max = Math.Max(a_Wave.StartY, a_Wave.EndY);
            double min = Math.Min(a_Wave.StartY, a_Wave.EndY);
            double high = max - GlobalVar.SignalWaveHeight * GlobalVar.StandardWaveHighLowPercent;
            double low = min + GlobalVar.SignalWaveHeight * GlobalVar.StandardWaveHighLowPercent;

            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_Wave.StartX, high);
            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_Wave.EndX, high);

            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_Wave.StartX, low);
            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_Wave.EndX, low);
        }

        private void SetSignalWaveOnChart(EasyTrader.Wave.PriceWave a_Wave, double a_HighVal, double a_LowVal)
        {
            if (a_Wave == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["기상위"].Points.Clear();
            SimulationChartCtrl.Series["기하위"].Points.Clear();

            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_Wave.StartX, a_HighVal);
            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_Wave.EndX, a_HighVal);

            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_Wave.StartX, a_LowVal);
            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_Wave.EndX, a_LowVal);
        }

        private void SetRegWaveOnChart(EasyTrader.Wave.PriceWave a_IndexWave, EasyTrader.Signal.ForecastingInfo a_SigInfo)
        {
            if (a_IndexWave == null)
                return;

            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["현재평균파"].Points.Clear();
            SimulationChartCtrl.Series["신호평균파"].Points.Clear();

            SimulationChartCtrl.Series["현재평균파"].Points.AddXY(a_IndexWave.StartX, a_IndexWave.StartY);
            SimulationChartCtrl.Series["현재평균파"].Points.AddXY(a_IndexWave.EndX, a_IndexWave.EndY);

            SimulationChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.StartX, a_SigInfo.StartY);
            SimulationChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.EndX, a_SigInfo.EndY);
        }

        private void SetSignalWaveOnChart(PriceWaveList a_WaveList)
        {
            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["신호파동"].Points.Clear();
            for (int i = 0; i < a_WaveList.Count; i++)
            {
                EasyTrader.Wave.PriceWave wave = a_WaveList[i];
                SimulationChartCtrl.Series["신호파동"].Points.AddXY(wave.StartX, wave.StartY);
                // 파동은 마지막 점을 한번 더 넣어 준다.
                if (i == a_WaveList.Count - 1)
                {
                    SimulationChartCtrl.Series["신호파동"].Points.AddXY(wave.EndX, wave.EndY);
                }
            }
        }
        private void InitControl()
        {
            for (int i = 0; i < GlobalVar.SysNameArray.Length; i++)
                comboSystem.Items.Add(GlobalVar.SysNameArray[i]);
            comboSystem.SelectedIndex = m_SysType;

            comboFirstSignal.SelectedIndex = 0;

            SimulationChartCtrl.Series["지수"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["파동"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["최고"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["최저"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["상위"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["하위"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["현재평균파"].ToolTip = "#VALX : #VAL";
            SimulationChartCtrl.Series["신호평균파"].ToolTip = "#VALX : #VAL";

            SimulationChartCtrl.Series["최고"].Enabled = false;
            SimulationChartCtrl.Series["최저"].Enabled = false;
            SimulationChartCtrl.Series["상위"].Enabled = false;
            SimulationChartCtrl.Series["하위"].Enabled = false;

            cbShowWave.Checked = true;
            cbShowPrice.Checked = false;
            cbForecasting.Checked = true;
            cbPrice.Checked = true;
            cbMax.Checked = false;
            cbMin.Checked = false;
            cbHigh.Checked = false;
            cbLow.Checked = false;
            cbCurWaveReg.Checked = true;
            cbSigWaveReg.Checked = true;

            //SimulationChartCtrl.EnableZoomAndPanControls(ChartCursorSelected, ChartCursorMoved);
            cbZoom.Checked = false;
            if (m_ShowSignal == true)
            {
                cbShowSignal.Checked = true;
            }
            else
            {
                cbShowSignal.Checked = false;
            }
            /*
            int selectedIndex = comboRegression.FindString(GlobalVar.RegressionType);
            comboRegression.SelectedIndex = selectedIndex;

            nudReferenceRange.Value = GlobalVar.ReferenceRange;

            cbForecasting.Checked = false;
            if (cbForecasting.Checked == true)
            {
                labelReferenceRange.Enabled = true;
                nudReferenceRange.Enabled = true;
                SimulationChartCtrl.Series["Forecasting"].Enabled = true;
                SimulationChartCtrl.Series["ErrorRange"].Enabled = true;
            }
            else
            {
                labelReferenceRange.Enabled = false;
                nudReferenceRange.Enabled = false;
                SimulationChartCtrl.Series["Forecasting"].Enabled = false;
                SimulationChartCtrl.Series["ErrorRange"].Enabled = false;
            }

            if (GlobalVar.LiquidApply == true)
            {
                cbLiquidApply.Checked = true;
            }
            else
            {
                cbLiquidApply.Checked = false;
            }*/
        }

        private void ChartCursorSelected(double x, double y)
        {
            int curIndex = (int)x;
            int pointCount = SimulationChartCtrl.Series["지수"].Points.Count;
            if (curIndex <= 0 || curIndex >= pointCount)
                return;
            string curTime = SimulationChartCtrl.Series["지수"].Points[curIndex].AxisLabel;
            string minText = curTime.Substring(curTime.Length - 2, 2);
            string hourText = curTime.Substring(0, curTime.Length - 2);

            txtChartSelect.Text = "선택된 값 : " + hourText + "시 " + minText + "분 , " + y.ToString("F2");
        }
        private void ChartCursorMoved(double x, double y)
        {
            int curIndex = (int)x;
            int pointCount = SimulationChartCtrl.Series["지수"].Points.Count;
            if (curIndex <= 0 || curIndex >= pointCount)
                return;
            string curTime = SimulationChartCtrl.Series["지수"].Points[curIndex].AxisLabel;
            string minText = curTime.Substring(curTime.Length - 2, 2);
            string hourText = curTime.Substring(0, curTime.Length - 2);

            txtChartValue.Text = "   마우스위치 : " + hourText + "시 " + minText + "분 , " + y.ToString("F2");
        }
        
        // 여기서 차트를 갱신해 준다.
        private void OnTimerTick(object sender, EventArgs e)
        {
            if (m_Started == true && GlobalVar.OperationMode == GlobalVar.OperationModeSimul)
            {
                GlobalVar.SimulIndex = m_CurIndex;
                SetChartData(m_CurIndex);
                // 파동을 그려준다.
                if (m_WaveManager != null)
                {
                    // 파동을 만들어 놓는다.
                    //m_WaveManager.MakeWaveListFromFutOptChart(m_CurIndex + 1);
                    //PriceWaveList curWaveList = m_EasyTraderSignalManager.ETWaveSignalManager.EasyTraderWaveManager.ArragedWaveList;
                    //SetWaveOnChart(curWaveList);
                }

                ShowCurValue(m_CurIndex);
                
                string valueText = "";
                if (GlobalVar.ProgressVal > 0)
                {
                    signalProgressBar.StartColor = Color.Red;
                    signalProgressBar.EndColor = Color.Red;
                    valueText = "매수 : ";
                }
                else
                {
                    signalProgressBar.StartColor = Color.Blue;
                    signalProgressBar.EndColor = Color.Blue;
                    valueText = "매도 : ";
                }

                signalProgressBar.Value = Math.Abs(GlobalVar.ProgressVal);
                valueText += signalProgressBar.Value.ToString();
                valueText += "%";
                signalProgressBar.ValueText = valueText;

                //SetForecastingYOnChart(m_CurIndex);

                if (m_CPDataSet != null)
                {
                    m_EasyTraderSignalManager.ETWaveSignalManager.EasyTraderDataSet = m_CPDataSet;
                    m_EasyTraderSignalManager.ETHogaSignalManager.EasyTraderDataSet = m_CPDataSet;
                    m_EasyTraderSignalManager.ETSubjectSignalManager.EasyTraderDataSet = m_CPDataSet;
                    m_EasyTraderSignalManager.ETHighLowSignalManager.EasyTraderDataSet = m_CPDataSet;
                    m_EasyTraderSignalManager.CurIndex = m_CurIndex;

                    // 가격 상태를 갱신한다.
                    m_EasyTraderSignalManager.UpdateAllPriceState();
                    // 시스템의 상태를 갱신한다.
                    m_EasyTraderSignalManager.UpdateSysState();

                    ShowProfit(m_CurIndex);
                    PriceWaveList curWaveList = m_EasyTraderSignalManager.ETWaveSignalManager.EasyTraderWaveManager.ArragedWaveList;
                    SetWaveOnChart(curWaveList);
                    
                }

                m_CurIndex++;
                if (m_CurIndex >= GlobalVar.MaxDayIndex - 1)
                {
                    timer.Stop();
                }
            }
        }

        private void SetRegWaveOnChart(EasyTrader.Signal.ForecastingInfo a_CurInfo, EasyTrader.Signal.ForecastingInfo a_SigInfo)
        {
            if (a_CurInfo == null || a_SigInfo == null)
                return;

            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["현재평균파"].Points.Clear();
            SimulationChartCtrl.Series["신호평균파"].Points.Clear();

            SimulationChartCtrl.Series["현재평균파"].Points.AddXY(a_CurInfo.StartX, a_CurInfo.StartY);
            SimulationChartCtrl.Series["현재평균파"].Points.AddXY(a_CurInfo.EndX, a_CurInfo.EndY);

            SimulationChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.StartX, a_SigInfo.StartY);
            SimulationChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.EndX, a_SigInfo.EndY);
        }

        private void SetSignalHeightOnChart(EasyTrader.Signal.ForecastingInfo a_ForeInfo, EasyTrader.Signal.HighLowInfo a_HighLowInfo)
        {
            if (a_ForeInfo == null || a_HighLowInfo == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            SimulationChartCtrl.Series["기상위"].Points.Clear();
            SimulationChartCtrl.Series["기하위"].Points.Clear();

            double highLimit = 0.0;
            double lowLimit = 0.0;
            double firstHighY = 0.0;
            double firstLowY = 0.0;
            double secondLowY = 0.0;
            double secondHighY = 0.0;
            double lowRootLimit = a_HighLowInfo.LowY + GlobalVar.WaveRootLimit;
            double highRootlLimit = a_HighLowInfo.HighY - GlobalVar.WaveRootLimit;
            if (a_HighLowInfo.MinMaxHeight() >= GlobalVar.MaxCloseHeight)
            {
                firstHighY = a_HighLowInfo.HighY - GlobalVar.MinHighLowTransHeight;
                firstLowY = a_HighLowInfo.LowY + GlobalVar.MinHighLowTransHeight;
                secondHighY = a_HighLowInfo.CloseMax - GlobalVar.MinCloseTransHeight;
                secondLowY = a_HighLowInfo.CloseMin + GlobalVar.MinCloseTransHeight;
            }
            else
            {
                firstHighY = a_HighLowInfo.HighY - GlobalVar.MinHighLowHeight;
                firstLowY = a_HighLowInfo.LowY + GlobalVar.MinHighLowHeight;
                secondHighY = a_HighLowInfo.CloseMax - GlobalVar.MinCloseHeight;
                secondLowY = a_HighLowInfo.CloseMin + GlobalVar.MinCloseHeight;
            }

            lowLimit = Math.Max(firstLowY, secondLowY);
            highLimit = Math.Min(firstHighY, secondHighY);

            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_ForeInfo.StartX, highLimit);
            SimulationChartCtrl.Series["기상위"].Points.AddXY(a_ForeInfo.EndX, highLimit);

            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_ForeInfo.StartX, lowLimit);
            SimulationChartCtrl.Series["기하위"].Points.AddXY(a_ForeInfo.EndX, lowLimit);
        }

        private void ShowCurValue(int a_CurIndex)
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null)
                return;

            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0 || rowCount - 1 < a_CurIndex)
                return;
            txtSimulOrder.Text = GlobalVar.SimulOrderMessage;

            DataRow row = dataTable.Rows[a_CurIndex];
            double closeValue = Convert.ToDouble(row["종가"]);
            string curTime = row["시각"].ToString();
            double stdVal = m_CPDataSet.FindTodayBase();
            if (curTime != "0")
            {
                string minText = curTime.Substring(curTime.Length - 2, 2);
                string hourText = curTime.Substring(0, curTime.Length - 2);

                txtCurTime.Text = "현재시간 " + hourText + " : " + minText;
                txtCurPrice.Text = "현재가격 " + closeValue.ToString("F2") + " , 기준가 : " + stdVal.ToString("F2");
                txtReverseRatio.Text = "반발계수 : " + GlobalVar.ReverseRatio.ToString("F2");
                txtPriceAngle.Text = "현재 값각도 : " + GlobalVar.PriceAngle.ToString("F2");
                if (m_EasyTraderSignalManager.CurWave != null)
                {
                    txtSigWaveRegHeight.Text = "현재신호파높이 : " + m_EasyTraderSignalManager.LastSignalRegression.Height().ToString("F2");
                    txtCurWaveRegHeight.Text = "현재평균파높이 : " + m_EasyTraderSignalManager.CurWaveRegression.Height().ToString("F2");
                    txtCurWaveHeight.Text = "현재파동높이 : " + m_EasyTraderSignalManager.CurWave.Height().ToString("F2");
                }
            }

            tbSumDown.Text = m_EasyTraderSignalManager.WaveSumDown.ToString("F2");
            tbSumUp.Text = m_EasyTraderSignalManager.WaveSumUp.ToString("F2");
            tbCrossCount.Text = m_EasyTraderSignalManager.CrossCount.ToString();
        }

        private void ShowProfit(int a_CurIndex)
        {
            if (m_EasyTraderSignalManager == null || m_CPDataSet == null)
                return;
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0 || rowCount - 1 < a_CurIndex)
                return;

            DataRow row = dataTable.Rows[a_CurIndex];
            double closeValue = Convert.ToDouble(row["종가"]);

            double curProfit = m_EasyTraderSignalManager.CalcCurProfit(m_EasyTraderSignalManager.FindSignalList(m_SysType), closeValue);
            double totalProfit = m_EasyTraderSignalManager.CalcTotalProfit(m_EasyTraderSignalManager.FindSignalList(m_SysType), closeValue);

            txtCurProfit.Text = "현재수익 : " + curProfit.ToString("F2") + " 만원";
            txtTotalProfit.Text = "전체수익 : " + totalProfit.ToString("F2") + " 만원";
        }

        private void SetForecastingYOnChart(int a_CurIndex)
        {
            if (m_EasyTraderSignalManager.ETWaveSignalManager == null)
                return;

            int result = m_EasyTraderSignalManager.ETWaveSignalManager.GetForecastingInfo(m_ForecastInfo, "종가", GlobalVar.RegressionType, a_CurIndex, GlobalVar.PriceReferenceRange, false);
            if (SimulationChartCtrl.Series["Forecasting"] != null && result > 0 && m_ForecastInfo != null)
            {
                SimulationChartCtrl.Series["Forecasting"].Points.Clear();
                SimulationChartCtrl.Series["Forecasting"].Points.AddXY(m_ForecastInfo.StartX, m_ForecastInfo.StartY);
                SimulationChartCtrl.Series["Forecasting"].Points.AddXY(m_ForecastInfo.EndX, m_ForecastInfo.EndY);
            }
        }

        private void SetChartData(int a_CurIndex)
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null)
                return;

            SimulationChartCtrl.Series["지수"].Points.Clear();
            SimulationChartCtrl.Series["최고"].Points.Clear();
            SimulationChartCtrl.Series["최저"].Points.Clear();
            SimulationChartCtrl.Series["상위"].Points.Clear();
            SimulationChartCtrl.Series["하위"].Points.Clear();
            SimulationChartCtrl.Series["이동평균"].Points.Clear();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            if (dataTable == null)
                return;

            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0 || rowCount - 1 < a_CurIndex)
                return;

            double highValue = 0;
            double lowValue = 0;
            double openValue = dataTable.GetOpenVal();
            double closeValue = 0;
            double stdVal = m_CPDataSet.FindTodayBase();
            /*
            // 시작값이 있을 때는 시작값을 설정해 준다.
            if (openValue != 0)
            {
                if (curChartType == 0)
                {
                    SimulationChartCtrl.Series["지수"].Points.AddXY(0, openValue);
                    SimulationChartCtrl.Series["지수"].Points[0].XValue = 0;
                    SimulationChartCtrl.Series["지수"].Points[0].AxisLabel = "900";
                    SimulationChartCtrl.Series["지수"].Points[0].YValues[1] = openValue;
                    SimulationChartCtrl.Series["지수"].Points[0].YValues[2] = openValue;
                    SimulationChartCtrl.Series["지수"].Points[0].YValues[3] = openValue;
                }
                else
                {
                    SimulationChartCtrl.Series["지수"].Points.AddXY(0, openValue);
                    SimulationChartCtrl.Series["지수"].Points[0].XValue = 0;
                    SimulationChartCtrl.Series["지수"].Points[0].AxisLabel = "900";
                }
            }*/
            for (int i = 0; i <= a_CurIndex; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["종가"] == DBNull.Value)
                        continue;
                    closeValue = Convert.ToDouble(row["종가"]);
                    // 값이 0이라는 것은 값을 얻어오지 못했다는 것이므로 여기서 그만한다.
                    if (closeValue == 0)
                        continue;

                    //Console.WriteLine(closeValue.ToString("F2"));
                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    if (i == 0)
                    {
                        maxValue = highValue;
                        minValue = lowValue;
                    }
                    if (curChartType == 0)
                    {
                        SimulationChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        SimulationChartCtrl.Series["지수"].Points[i].XValue = i;
                        SimulationChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        SimulationChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        SimulationChartCtrl.Series["지수"].Points[i].XValue = i;
                        SimulationChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                    }
                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                    }

                    SimulationChartCtrl.Series["최저"].Points.AddXY(i, minValue);
                    SimulationChartCtrl.Series["최고"].Points.AddXY(i, maxValue);

                    double dayHeight = maxValue - minValue;
                    double highZone = maxValue - dayHeight * GlobalVar.HighLowPercent;
                    double lowZone = minValue + dayHeight * GlobalVar.HighLowPercent;

                    SimulationChartCtrl.Series["상위"].Points.AddXY(i, highZone);
                    SimulationChartCtrl.Series["하위"].Points.AddXY(i, lowZone);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            if (stdVal != 0 && stdVal > maxValue)
            {
                maxValue = stdVal;
            }
            if (stdVal != 0 && stdVal < minValue)
            {
                minValue = stdVal;
            }

            double valueHeight = maxValue - minValue;
            double ceilVal = Math.Ceiling(valueHeight);
            maxValue = minValue + ceilVal;

            if (maxValue >= minValue)
            {
                SimulationChartCtrl.ChartAreas["Price"].AxisY.Minimum = minValue;
                SimulationChartCtrl.ChartAreas["Price"].AxisY.Maximum = maxValue;
            }
            //if (SimulationChartCtrl.Series["지수"].Points.Count > 6)
            //    SimulationChartCtrl.DataManipulator.FinancialFormula(FinancialFormula.ExponentialMovingAverage, "5", "지수", "이동평균");
        }

        public void ShowForcasting()
        {
            if (ChartDataLoaded == false)
                return;
            // typeRegression is a string represented by one of the following strings:
            // "Linear", "Exponential", "Logarithmic", or "Power".
            // Polynomial is represented by an integer value in the form of a string.
            string typeRegression;

            // Defining the typeRegression.
            // This Statement can also be represented by the statement typeRegression = "2";
            typeRegression = "5";

            // The number of days for Forecasting.
            int forecasting = 10;

            // Show Error as a range chart.
            string error = "True";

            // Show Forecasting Error as a range chart.
            string forecastingError = "True";

            // Formula parameters
            string parameters = typeRegression + ',' + forecasting + ',' + error + ',' + forecastingError;

            // Create Forecasting Series.
            //SimulationChartCtrl.DataManipulator.FinancialFormula(FinancialFormula.Forecasting, parameters, "지수:Y", "Forecasting:Y,Range:Y,Range:Y2");

            SimulationChartCtrl.DataManipulator.FinancialFormula(FinancialFormula.Forecasting, parameters, "지수:Y", "Forecasting:Y");

            //SimulationChartCtrl.Series["Range"].ChartArea = "지수";
     

        }

        public void ShowForcasting(int a_DataCount)
        {
            if (SimulationChartCtrl.Series["지수"].Points.Count < 3)
                return;

            // typeRegression is a string represented by one of the following strings:
            // "Linear", "Exponential", "Logarithmic", or "Power".
            // Polynomial is represented by an integer value in the form of a string.
            string typeRegression;

            // Defining the typeRegression.
            // This Statement can also be represented by the statement typeRegression = "2";
            typeRegression = "3";

            // The number of days for Forecasting.
            int forecasting = 0;

            // Show Error as a range chart.
            string error = "True";

            // Show Forecasting Error as a range chart.
            string forecastingError = "False";

            // Formula parameters
            string parameters = typeRegression + ',' + forecasting + ',' + error + ',' + forecastingError;

            // Create Forecasting Series.
            SimulationChartCtrl.DataManipulator.FinancialFormula(FinancialFormula.Forecasting, parameters, "지수:Y", "Forecasting:Y,Range:Y,Range:Y2");

            //SimulationChartCtrl.Series["Range"].ChartArea = "지수";


        }

        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null || GlobalVar.FutOptChartDataDownloaded == false)
                return;

            SimulationChartCtrl.Series["지수"].Points.Clear();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            int minIndex = 0;
            int maxIndex = 0;
            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["종가"] == DBNull.Value)
                        continue;
                    closeValue = Convert.ToDouble(row["종가"]);
                    // 값이 0이라는 것은 값을 얻어오지 못했다는 것이므로 여기서 그만한다.
                    if (closeValue == 0)
                        break;

                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    if (curChartType == 0)
                    {
                        SimulationChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        SimulationChartCtrl.Series["지수"].Points[i].XValue = i;
                        SimulationChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        SimulationChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        SimulationChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        SimulationChartCtrl.Series["지수"].Points[i].XValue = i;
                        SimulationChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                        maxIndex = i;
                    }
                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                        minIndex = i;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            double valueHeight = maxValue - minValue;
            double ceilVal = Math.Ceiling(valueHeight);
            maxValue = minValue + ceilVal;

            if (maxValue >= minValue)
            {
                SimulationChartCtrl.ChartAreas["Price"].AxisY.Minimum = minValue;
                SimulationChartCtrl.ChartAreas["Price"].AxisY.Maximum = maxValue;
            }

            ChartDataLoaded = true;
        }

        public SimulationFrm(ETDataSet a_DataSet)
        {
            InitializeComponent();
            m_CPDataSet = a_DataSet;
            InitControl();
        }

        private void InitChart()
        {
            SimulationChartCtrl.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            SimulationChartCtrl.BackSecondaryColor = System.Drawing.Color.White;
            SimulationChartCtrl.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            SimulationChartCtrl.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            SimulationChartCtrl.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            SimulationChartCtrl.BorderlineWidth = 2;
            SimulationChartCtrl.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            SimulationChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.Interval = 10;
            SimulationChartCtrl.ChartAreas["Price"].AxisX.Interval = 10;
            SimulationChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.Interval = 1;
            SimulationChartCtrl.ChartAreas["Price"].AxisY.Interval = 1;

            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.IsClustered = true;
            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.Perspective = 10;
            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.IsRightAngleAxes = false;
            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.WallWidth = 0;
            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.Inclination = 15;
            SimulationChartCtrl.ChartAreas["Price"].Area3DStyle.Rotation = 10;
            SimulationChartCtrl.ChartAreas["Price"].AxisX.IsLabelAutoFit = true;
            SimulationChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            SimulationChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = false;
            SimulationChartCtrl.ChartAreas["Price"].AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            SimulationChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            SimulationChartCtrl.ChartAreas["Price"].AxisY.IsLabelAutoFit = true;
            SimulationChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            SimulationChartCtrl.ChartAreas["Price"].AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            SimulationChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            SimulationChartCtrl.ChartAreas["Price"].AxisY.IsStartedFromZero = false;
            //SimulationChartCtrl.ChartAreas["Price"].AxisY.LabelAutoFitMaxFontSize;
            SimulationChartCtrl.ChartAreas["Price"].BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            SimulationChartCtrl.ChartAreas["Price"].BackSecondaryColor = System.Drawing.Color.White;
            SimulationChartCtrl.ChartAreas["Price"].BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            SimulationChartCtrl.ChartAreas["Price"].BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            SimulationChartCtrl.ChartAreas["Price"].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            SimulationChartCtrl.ChartAreas["Price"].Position.Auto = true;
            //SimulationChartCtrl.ChartAreas["Price"].Position.Height = 80F;
            //SimulationChartCtrl.ChartAreas["Price"].Position.Width = 80F;
            //SimulationChartCtrl.ChartAreas["Price"].Position.X = 5F;
            //SimulationChartCtrl.ChartAreas["Price"].Position.Y = 10F;
            SimulationChartCtrl.ChartAreas["Price"].ShadowColor = System.Drawing.Color.Transparent;
            //SimulationChartCtrl.ChartAreas["Price"].BackImage = "Cre.jpg";
            DateTime now = DateTime.Now;
            if (now.Year == GlobalVar.YearLimit && now.Month >= GlobalVar.MonthLimit)
            {
                SimulationChartCtrl.ChartAreas["Price"].BackImage = "Credential.jpg";
            }
            if (GlobalVar.SimulationChartType == 0)
            {
                SimulationChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                comboSimulationChartType.SelectedIndex = 0;
            }
            else
            {
                SimulationChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                comboSimulationChartType.SelectedIndex = 1;
            }

            SimulationChartCtrl.Series[1]["PriceUpColor"] = "Red";
            SimulationChartCtrl.Series[1]["PriceDownColor"] = "Blue";
            SimulationChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = true;
            SimulationChartCtrl.ChartAreas["Price"].AxisX.IsMarginVisible = true;
            SimulationChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.IsEndLabelVisible = true;
            SimulationChartCtrl.ChartAreas["Price"].AxisY.IsMarginVisible = true;
            //SimulationChartCtrl.Series[0].Color = Color.Red;
            //DataPointCustomProperties aa = SimulationChartCtrl.Series[0]["PriceUpColor"];
        }

        private void SimulationFrm_Load(object sender, EventArgs e)
        {
            InitChart();
            InitTimer();
            curChartType = GlobalVar.FutOptChartType;
            m_EasyTraderSignalManager.EasyTraderDataSet = m_CPDataSet;
            m_EasyTraderSignalManager.ETWaveSignalManager.EasyTraderDataSet = m_CPDataSet;
            m_EasyTraderSignalManager.ETHogaSignalManager.EasyTraderDataSet = m_CPDataSet;
            m_EasyTraderSignalManager.ETSubjectSignalManager.EasyTraderDataSet = m_CPDataSet;
            m_EasyTraderSignalManager.ETHighLowSignalManager.EasyTraderDataSet = m_CPDataSet;

            // 이벤트 핸들러를 등록해 준다.
            m_EasyTraderSignalManager.LastSignalFired += new SysManagerEventHandler(this.SysManager_OnLastSignalFired);

            m_WaveManager.EasyTraderDataSet = m_CPDataSet;
            // 차트에 데이터를 대응시켜 준다.
            //SetChartData();
            m_SysName = GlobalVar.SysNameArray[m_SysType];
            this.Text = m_SysName;
        }

        private void SimulationFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Stop();

            // 모든 시스템의 자동 주문을 해제하여 준다.
            GlobalVar.ClearAllAutoOrder();
        }

        private void comboSimulationChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            curChartType = comboSimulationChartType.SelectedIndex;
            if (curChartType != -1)
            {
                if (curChartType == 0)
                {
                    SimulationChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                }
                else
                {
                    SimulationChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                }
                SetChartData();
                SimulationChartCtrl.Invalidate();
            }
        }

        private void cbShowWave_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowWave.Checked)
            {
                SimulationChartCtrl.Series["파동"].Enabled = true;
            }
            else
            {
                SimulationChartCtrl.Series["파동"].Enabled = false;
            }
        }

        private void cbShowPrice_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series.FindByName("지수");
            if (series == null)
                return;
            if (cbShowPrice.Checked == true)
            {
                SimulationChartCtrl.Series["지수"].IsValueShownAsLabel = true;
                SimulationChartCtrl.Series["지수"].Label = "#VALX : #VAL{G5}";
            }
            else
            {
                SimulationChartCtrl.Series["지수"].IsValueShownAsLabel = false;
                SimulationChartCtrl.Series["지수"].Label = "";
            }
        }

        private void cbZoom_CheckedChanged(object sender, EventArgs e)
        {
            if (cbZoom.Checked)
            {
                SimulationChartCtrl.EnableZoomAndPanControls(ChartCursorSelected, ChartCursorMoved);
            }
            else
            {
                SimulationChartCtrl.DisableZoomAndPanControls();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer.Stop();
            m_Started = false;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            m_EasyTraderSignalManager.ClearSignalList();
            m_CurIndex = 0;
            //m_SignalManager.ClearSignalWaveList();
            //m_SignalManager.ClearSignalList();
            m_Started = true;
        }

        private void nudTimerInterval_ValueChanged(object sender, EventArgs e)
        {
            timer.Interval = (int)nudTimerInterval.Value;
        }

        private void SimulationChartCtrl_PostPaint(object sender, ChartPaintEventArgs e)
        {
            if (m_SysType < 0)
                return;
            if (m_ShowMainSignal)
            {
                PriceSignalList signalList = m_EasyTraderSignalManager.SysManagerList[m_SysType].PriceSignalList;
                DrawSignal(signalList, e);
            }

            if (m_ShowSignal)
            {
                PriceSignalList signalList = m_EasyTraderSignalManager.SysManagerList[m_SysType].PriceStateList;
                DrawSignal(signalList, e);
            }
            DateTime now = DateTime.Now;
            if (now.Year == GlobalVar.YearLimit && now.Month >= GlobalVar.MonthLimit)
            {
                DrawCredential(e);
            }
        }

        private void cbShowSignal_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowSignal.Checked)
                m_ShowSignal = true;
            else
                m_ShowSignal = false;
        }

        private void cbForecasting_CheckedChanged(object sender, EventArgs e)
        {
            /*
            if (cbForecasting.Checked == true)
            {
                labelReferenceRange.Enabled = true;
                nudReferenceRange.Enabled = true;
                SimulationChartCtrl.Series["Forecasting"].Enabled = true;
                SimulationChartCtrl.Series["ErrorRange"].Enabled = true;
            }
            else
            {
                labelReferenceRange.Enabled = false;
                nudReferenceRange.Enabled = false;
                SimulationChartCtrl.Series["Forecasting"].Enabled = false;
                SimulationChartCtrl.Series["ErrorRange"].Enabled = false;
            }*/
        }

        private void comboRegression_SelectedIndexChanged(object sender, EventArgs e)
        {
            //GlobalVar.RegressionType = comboRegression.SelectedItem.ToString();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (m_CPDataSet == null)
                return;

            DateTime curDate = dateTimePickerCtrl.Value;
            m_CPDataSet.ReadTablesFromXML(curDate);
        }

        private void cbPrice_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series["지수"];
            if (series == null)
                return;
            if (cbPrice.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbMax_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series["최고"];
            if (series == null)
                return;
            if (cbMax.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbMin_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series["최저"];
            if (series == null)
                return;
            if (cbMin.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbHigh_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series["상위"];
            if (series == null)
                return;
            if (cbHigh.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbLow_CheckedChanged(object sender, EventArgs e)
        {
            Series series = SimulationChartCtrl.Series["하위"];
            if (series == null)
                return;
            if (cbLow.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void nudReferenceRange_ValueChanged(object sender, EventArgs e)
        {
            ;
        }

        private void cbLiquidApply_CheckedChanged(object sender, EventArgs e)
        {
            /*
            string selText = "";
            if (cbLiquidApply.Checked == true)
            {
                selText = "True";
                GlobalVar.LiquidApply = true;
            }
            else
            {
                selText = "False";
                GlobalVar.LiquidApply = false;
            }


            string regSubkey = "Software\\EasyTrader\\Order";
            // 서브키를 얻어온다. 없으면 null
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(regSubkey, true);
            // 없으면 서브키를 만든다.
            if (rk == null)
            {
                // 해당이름으로 서브키 생성
                rk = Registry.CurrentUser.CreateSubKey(regSubkey);
            }

            // 서브키 아래 값 쓰기
            rk.SetValue("LiquidApply", selText);
             */
        }

        private void cbCurWaveReg_CheckedChanged(object sender, EventArgs e)
        {
            if (cbCurWaveReg.Checked)
            {
                SimulationChartCtrl.Series["현재평균파"].Enabled = true;
            }
            else
            {
                SimulationChartCtrl.Series["현재평균파"].Enabled = false;
            }
        }

        private void cbSigWaveReg_CheckedChanged(object sender, EventArgs e)
        {
            if (cbSigWaveReg.Checked)
            {
                SimulationChartCtrl.Series["신호평균파"].Enabled = true;
            }
            else
            {
                SimulationChartCtrl.Series["신호평균파"].Enabled = false;
            }
        }

        private bool m_ShowMainSignal = false;

        private void cbShowMainSignal_CheckedChanged(object sender, EventArgs e)
        {
             if (cbShowMainSignal.Checked)
                 m_ShowMainSignal = true;
             else
                 m_ShowMainSignal = false;
        }

        private string GetSystemName()
        {
            string msg = "_";
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                msg += GlobalVar.SysName0;
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                msg += GlobalVar.SysName1;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                msg += GlobalVar.SysName2;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                msg += GlobalVar.SysName3;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                msg += GlobalVar.SysName4;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                msg += GlobalVar.SysName5;
            }
            msg += "_" + m_HashCode.ToString();

            return msg;
        }

        private string GetSystemLogFileName()
        {
            string msg = "_";
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                msg += GlobalVar.SysName0;
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                msg += GlobalVar.SysName1;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                msg += GlobalVar.SysName2;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                msg += GlobalVar.SysName3;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                msg += GlobalVar.SysName4;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                msg += GlobalVar.SysName5;
            }
            msg += "_" + m_HashCode.ToString() + "_Log.txt";

            return msg;
        }

        private void btnSysSet_Click(object sender, EventArgs e)
        {
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                EasyTrader.Form.JisuWaveHogaSummitSysSetFrm signalSettingFrm = new EasyTrader.Form.JisuWaveHogaSummitSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                EasyTrader.Form.JisuWaveSysSetFrm signalSettingFrm = new EasyTrader.Form.JisuWaveSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                EasyTrader.Form.HogaWaveSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaWaveSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                EasyTrader.Form.HogaSquareOccSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaSquareOccSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                EasyTrader.Form.HogaSummitSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaSummitSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                EasyTrader.Form.CallPutSquareOccSysSetFrm signalSettingFrm = new EasyTrader.Form.CallPutSquareOccSysSetFrm();
                signalSettingFrm.Show();
            }
        }

        private void comboFirstSignal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboFirstSignal.SelectedIndex == 0)
            {
                m_FirstSig = GlobalVar.FirstSigByHogaAngle;
            }
            else if (comboFirstSignal.SelectedIndex == 1)
            {
                m_FirstSig = GlobalVar.FirstSigByJisu;
            }
            else if (comboFirstSignal.SelectedIndex == 2)
            {
                m_FirstSig = GlobalVar.FirstSigByHogaDelta;
            }
            else if (comboFirstSignal.SelectedIndex == 3)
            {
                m_FirstSig = GlobalVar.FirstSigByWaveCount;
            }
            else if (comboFirstSignal.SelectedIndex == 4)
            {
                m_FirstSig = GlobalVar.FirstSigByHogaAngleNHeight;
            }
            else if (comboFirstSignal.SelectedIndex == 5)
            {
                m_FirstSig = GlobalVar.FirstSigByHogaDeltaNHeight;
            }
            else if (comboFirstSignal.SelectedIndex == 6)
            {
                m_FirstSig = GlobalVar.FirstSigByWaveCounNHeight;
            }
            else
            {
                m_FirstSig = GlobalVar.FirstSigByHogaAngleNHeight;
            }

            JisuWaveHogaSummitSysVar.FirstSignalType = m_FirstSig;

            string regSubkey = "Software\\EasyTrader\\HogaJisuSys";
            // 서브키를 얻어온다. 없으면 null
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(regSubkey, true);
            // 없으면 서브키를 만든다.
            if (rk == null)
            {
                // 해당이름으로 서브키 생성
                rk = Registry.CurrentUser.CreateSubKey(regSubkey);
            }

            // 서브키 아래 값 쓰기
            rk.SetValue("FirstSignalType", JisuWaveHogaSummitSysVar.FirstSignalType.ToString());
        }

        private void btnFirstSigSet_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Form frmchild = new EasyTrader.Form.FirstSigSetFrm();
            frmchild.Show();
        }

        private void comboAcceptSignal_SelectedIndexChanged(object sender, EventArgs e)
        {
            ;
        }

        private void comboSystem_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboSystem.SelectedIndex < 0)
                m_SysType = 0;
            else
                m_SysType = comboSystem.SelectedIndex;
            m_SysName = GlobalVar.SysNameArray[m_SysType];
            this.Text = m_SysName;

            bool autoOrder = false;
            if (m_SysType == 0)
            {
                autoOrder = JisuWaveHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 1)
            {
                autoOrder = JisuWaveSysVar.AutoOrder;
            }
            else if (m_SysType == 2)
            {
                autoOrder = HogaWaveSysVar.AutoOrder;
            }
            else if (m_SysType == 3)
            {
                autoOrder = HogaSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == 4)
            {
                autoOrder = HogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 5)
            {
                autoOrder = CallPutSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == 6)
            {
                autoOrder = PureHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 7)
            {
                autoOrder = LooseHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 8)
            {
                autoOrder = CallPutInvDivSysVar.AutoOrder;
            }
            else if (m_SysType == 9)
            {
                autoOrder = TipAttackSysVar.AutoOrder;
            }
            else if (m_SysType == 10)
            {
                autoOrder = OptPriceSysVar.AutoOrder;
            }

            if (autoOrder == true)
            {
                cbAutoOrder.Checked = true;
            }
            else
            {
                cbAutoOrder.Checked = false;
            }
        }

        private void cbAutoOrder_CheckedChanged(object sender, EventArgs e)
        {
            bool autoOrder = false;
            if (cbAutoOrder.Checked == true)
            {
                autoOrder = true;
            }
            else
            {
                autoOrder = false;
            }

            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                JisuWaveHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                JisuWaveSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                HogaWaveSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                HogaSquareOccSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                HogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                CallPutSquareOccSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypePureHogaSummit)
            {
                PureHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeLooseHogaSummit)
            {
                LooseHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutInvDiv)
            {
                CallPutInvDivSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeTipAttack)
            {
                TipAttackSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptPrice)
            {
                OptPriceSysVar.AutoOrder = autoOrder;
            }
        }
    }
}
